﻿using System;
using AccelerateSensor.Model.Tools;

namespace AccelerateSensor.Model.Node
{
    /// <summary>
    /// 节点信息
    /// </summary>
    public class NodeInfo
    {
        /// <summary>
        /// 编号
        /// </summary>
        public string Uuid { get; set; }

        /// <summary>
        /// 网关编号
        /// </summary>
        public string GatewayUuid { get; set; }

        /// <summary>
        /// 设备类型
        /// </summary>
        public int Type { get; set; }

        /// <summary>
        /// 公有属性信息
        /// </summary>
        public NodeCommonAttributeInfo CommonAttributeInfo { get; set; }

        /// <summary>
        /// 私有属性信息
        /// </summary>
        public NodePrivateAttributeInfo PrivateAttributeInfo { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public NodeData Data { get; set; }

        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdateTime { get; set; }
        public DateTime LocalUpdateTime { get; set; }

        public string TypeString
        {
            get
            {
                var type = Enum.IsDefined(typeof(NodeType), Type)
                    ? (NodeType) Type
                    : NodeType.Unknown;
                var description = type.GetDescription();
                return string.IsNullOrWhiteSpace(description)
                    ? Type.ToString()
                    : description;
            }
        }

        public string PowerSource => CommonAttributeInfo?.PowerSourceString;

        public string PowerVoltage
        {
            get
            {
                var voltage = CommonAttributeInfo?.PowerVoltage ?? 0;
                return $"{voltage:F6}";
            }
        }

        public int NodeTemp => CommonAttributeInfo?.NodeTemp ?? 0;
        public int SleepTime => CommonAttributeInfo?.SleepTimeSec ?? 0;

        public void UpdateInfo(NodeInfo info)
        {
            GatewayUuid = info.GatewayUuid;
            Type = info.Type;
            UpdateTime = info.UpdateTime;

            if (info.CommonAttributeInfo != null)
            {
                CommonAttributeInfo = info.CommonAttributeInfo;
            }

            if (info.PrivateAttributeInfo != null)
            {
                PrivateAttributeInfo = info.PrivateAttributeInfo;
            }
        }

        public void UpdateData(NodeData data)
        {
            if (Data == null)
            {
                Data = data;
            }
            else
            {
                Data.UpdateData(data);
            }
        }
    }
}
